package server

import (
	"log"
	"math/rand/v2"

	"gitee.com/ameise84/e3net"
)

type Hd struct {
}

type Context struct {
	Close int
	Msg   int
}

func (ts *Context) OnRecv(conn e3net.Conn, bytes []byte) ([]byte, error) {
	log.Printf("server OnRecv:%s\n", string(bytes))
	conn.SendAsync(bytes)
	ts.Msg++
	if ts.Msg >= ts.Close && ts.Close <= 15 {
		conn.Close()
	}
	return nil, nil
}

func (ts *Hd) OnNewConnect(tag e3net.Tag, conn e3net.Conn) e3net.ConnContext {
	log.Println("new connect tag:", tag)
	return &Context{
		Close: 10 + rand.IntN(20),
	}
}

func (ts *Hd) OnClosedConnect(context e3net.ConnContext) {
	log.Println("OnClosedConnect")
}

func StartServer() (e3net.TcpServer, error) {
	s := e3net.NewTcpServer()
	s.AddAcceptor(&Hd{}, "1", ":3399", false, e3net.DefaultTcpAcceptorOptions())
	return s, s.Start()
}
